<?php
namespace App\Http\Controllers\Admin;

use App\Model\BannerModel;
Use App\Model\AdminLogsModel;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class BannerController extends Controller{
	//banner首页
    public function index(){
    	$list = BannerModel::OrderBy('sort','desc')->paginate(15);

    	return view('admin.banner.banner',compact('list'));
	}

	//添加
	public function add(){
    	return view('admin.banner.add');
	}
	public function insert(){
    	if(!request()->picname){
    		return ['code'=>0,'msg'=>'请上传banner'];
		}
    	DB::beginTransaction();
    	try{
    		$list = BannerModel::create([
    			'picname' => request()->picname,
				'oss_pic' => request()->picname,
			]);
    		DB::commit();
    		$msg = '添加banner信息(id:'.$list['id'].')';
    		AdminLogsModel::addLog($msg);
    		return ['code'=>1,'msg'=>'添加成功'];
		}catch(Exception $e){
    		DB::rollBack();
    		return ['code'=>0,'msg'=>'添加失败'];
		}
	}

	//删除Banner
	public function del(){
    	$banner = BannerModel::where('id',request()->id)->first();
    	DB::beginTransaction();
    	try{
    		@unlink(".".$banner['picname']);
    		BannerModel::where('id',request()->id)->delete();
    		DB::commit();
    		$msg = '删除banner信息(id:'.request()->id.')';
    		AdminLogsModel::addLog($msg);
    		return ['code'=>1,'msg'=>'删除成功'];
		}catch(Exception $e){
    		DB::rollBack();
    		return ['code'=>0,'msg'=>'删除失败'];
		}
	}

	//排序加载页面
	public function sort(){
    	$id = request()->id;
    	$sort = BannerModel::where('id',$id)->value('sort');
    	return view('admin.banner.sort',compact('id','sort'));
	}
	public function do_sort(){
		DB::beginTransaction();
		try{
			BannerModel::where('id',request()->id)->update([
				'sort' => request()->sort,
			]);
			DB::commit();
			return ['code'=>1,'msg'=>'已调整'];
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'操作失败'];
		}
	}

	//更改banner
	public function up_state(){
    	$state = ['1'=>'启用','2'=>'禁用'];
    	DB::beginTransaction();
    	try{
			BannerModel::where('id',request()->id)->update([
				'state' => request()->state,
			]);
    		DB::commit();
    		$msg = '编辑banner(id:'.request()->id.')状态为'.$state[request()->state];
    		AdminLogsModel::addLog($msg);
    		return ['code'=>1,'msg'=>'已'.$state[request()->state]];
		}catch(Exception $e){
    		DB::rollBack();
			return ['code'=>0,'msg'=>'操作失败'];
		};
	}
}